package com.gitee.wsl.ext.list


/**
 * Optional comparator for sorting, must be specified if `T` is not [Comparable].
 * @param list
 * List to insert into.
 * @param item
 * Item to insert.
 * @param <T>
 * Item type.
 *
 * @return Index to insert the item at to ensure sorted order.
 * Results are only correct if the list itself is already in sorted order.
</T> */
fun <T: Comparable<T>> sortedInsertIndex(list: List<T>, item: T): Int {
    if (list.isEmpty()) return 0
    var i: Int = binarySearch(list, item)
    if (i < 0) i = -i - 1 // When not found, invert to get correct index.
    return i
}

/**
 * @param list
 * List to insert into.
 * @param item
 * Item to insert.
 * @param <T>
 * Item type.
 *
 * @return `true` when inserted successfully.
</T> */
//fun <T : Comparable<T>> sortedInsert( list: MutableList<T>,  item: T): Boolean {
//    return sortedInsert(null, list, item)
//}

/**
 * @param comparator
 * Optional comparator for sorting, must be specified if `T` is not [Comparable].
 * @param list
 * List to insert into.
 * @param item
 * Item to insert.
// * @param <T>
// * Item type.
// *
// * @return `true` when inserted successfully.
//</T> */
fun <T: Comparable<T>> sortedInsert(list: MutableList<T>, item: T): Boolean {
    val index = sortedInsertIndex( list, item)
    if (index >= 0 && index <= list.size) {
        list.add(index, item)
        return true
    }
    return false
}